<?php
/**
 * Created by WXCH
 * Date: 2020/1/7 0007 22:00
 */

namespace app\admin\business;

use app\admin\model\Admin as AdminModel;
use think\Exception;

class Admin{

    public static function login($data){
        try{
            $adminModel = new AdminModel();
            $adminData = self::getAdminByUsername($data["username"]);
            if(empty($adminData)){
                throw new Exception("不存在该用户!");
            }
            //判断密码是否正确
            if($adminData['password'] != md5($data['password'])){
                throw new Exception("密码错误!");
            }
            $updateData = [
                "last_login_time" => time(),
                "last_login_ip" => request()->ip(),
                "update_time" => time()
            ];
            $res = $adminModel->updateAdminById($adminData["id"], $updateData);
            if(empty($res)){
                throw new Exception("登录失败!");
            }

        }catch (\Exception $ex){
            throw new Exception("内部异常，登录失败!");
        }

        //记录session
        session(config("session_admin"), $adminData);
        return true;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAdminByUsername($username){
        $adminModel = new AdminModel();
        $adminData = $adminModel->getAdminByUsername($username);
        if(empty($adminData) || ($adminData->status != config("status.mysql.table_normal"))){
            return false;
        }
        $adminData = $adminData->toArray();
        return $adminData;
    }
}